package com.example.controller;

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@Controller
public class MyCookieController {

    @GetMapping("/cookie")
    public String cookie(HttpServletResponse response, HttpSession session) {

        ServletUtil.addCookie(response, "cookie1", "aaaaaaaaaa");
        ServletUtil.addCookie(response, "test", "bbbbbb");

        Cookie cookie = new Cookie("httpOnly-co", "sssssssssss");
        cookie.setHttpOnly(true);
        ServletUtil.addCookie(response, cookie);

        Cookie cookie2 = new Cookie("secure-co", "sssssssssss");
        cookie2.setHttpOnly(true);
        cookie2.setSecure(true);
        ServletUtil.addCookie(response, cookie2);

        session.setAttribute("username", "uuuuuu");

        return "test";
    }

    @PostMapping("/postCookie")
    @ResponseBody
    public String postCookie(HttpServletRequest request, HttpSession session) {

        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(c -> System.out.println(c.getName() + " = " + c.getValue()));

        System.out.println("username == " + session.getAttribute("username"));

        Cookie test = ServletUtil.getCookie(request, "test");
        return "post cookie#test:" + test.getValue();
    }

    @PostMapping("/csrf-leak")
    @ResponseBody
    public String CSRFLeak(HttpServletRequest request, HttpSession session, @RequestParam boolean cf2_emc, @RequestParam String cf2_email) {

        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(c -> System.out.println(c.getName() + " = " + c.getValue()));

        System.out.println("2username == " + session.getAttribute("username"));
        System.out.println("cf2_emc == " + cf2_emc);
        System.out.println("cf2_email == " + cf2_email);

        return "11";
    }

}
